using Microsoft.EntityFrameworkCore;
using MESData.ErrorCode;
using MESData.Infrastucture;
using MESData.ProductionPlan.API.DTO;
using MESBaseis.Domain.ZSHH;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;

namespace MESData.ProductionPlan.API.Services
{
    /// <summary>
    /// 生产计划服务实现类
    /// </summary>
    public class ProductionPlanService : IProductionPlanService
    {
        private readonly MyDbcontext _context;
        private const string ExportRoot = "wwwroot/exports";

        public ProductionPlanService(MyDbcontext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增生产计划
        /// </summary>
        public async Task<ApiResult<bool>> CreateProductionPlanAsync(ProductionPlanDto dto, string operatorName)
        {
            try
            {
                // 使用执行策略包装整个事务单元，兼容 MySqlRetryingExecutionStrategy
                var strategy = _context.Database.CreateExecutionStrategy();
                await strategy.ExecuteAsync(async () =>
                {
                    using var transaction = await _context.Database.BeginTransactionAsync();
                    try
                    {
                        // 1. 新增生产计划主表
                        var productionPlan = new MESBaseis.Domain.ZSHH.ProductionPlan
                        {
                            PlanNumber = dto.PlanNumber,
                            PlanSubject = dto.PlanSubject,
                            DocumentDate = dto.DocumentDate,
                            SalesOrderId = dto.SalesOrderId,
                            ProjectId = dto.ProjectId,
                            Remarks = dto.Remarks,
                            IsBindSalesOrder = dto.IsBindSalesOrder,
                            Status = "草稿",
                            Creator = operatorName,
                            CreateTime = DateTime.Now
                        };

                        _context.ProductionPlans.Add(productionPlan);
                        await _context.SaveChangesAsync();

                        // 2. 新增生产计划物品（自由录入）
                        if (dto.ProductedItems?.Any() == true)
                        {
                            var productedItems = dto.ProductedItems.Select(item => new ProductedItem
                            {
                                ProductionPlanId = productionPlan.Id,
                                ItemNumber = item.ItemNumber,
                                ItemName = item.ItemName,
                                SpecificationModel = item.SpecificationModel,
                                Unit = item.Unit,
                                ItemCategory = item.ItemCategory,
                                ItemClassification = item.ItemClassification,
                                Brand = item.Brand,
                                Quantity = item.Quantity,
                                DetailDate = item.DetailDate,
                                MainUnitQuantity = item.MainUnitQuantity,
                                Remarks = item.Remarks,
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            }).ToList();

                            _context.ProductedItems.AddRange(productedItems);
                            await _context.SaveChangesAsync();

                            // 记录操作日志
                            _context.ProductionPlanOperationLogs.Add(new ProductionPlanOperationLog
                            {
                                ProductionPlanId = productionPlan.Id,
                                Operator = operatorName,
                                OperationTime = DateTime.Now,
                                OperationContent = $"新增生产物品，共{productedItems.Count}项",
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            });
                        }

                        // 3. 新增附件
                        if (dto.Attachments?.Any() == true)
                        {
                            var attachments = dto.Attachments.Select(att => new ProductionPlanAttachment
                            {
                                ProductionPlanId = productionPlan.Id,
                                FileName = att.FileName,
                                FilePath = att.FilePath,
                                UpdateTime = DateTime.Now,
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            }).ToList();

                            _context.ProductionPlanAttachments.AddRange(attachments);
                            await _context.SaveChangesAsync();

                            _context.ProductionPlanOperationLogs.Add(new ProductionPlanOperationLog
                            {
                                ProductionPlanId = productionPlan.Id,
                                Operator = operatorName,
                                OperationTime = DateTime.Now,
                                OperationContent = $"上传附件，共{attachments.Count}个文件",
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            });
                        }

                        // 4. 批量新增选择的物品 -> ProductionPlanItem
                        if (dto.SelectedItemIds?.Any() == true)
                        {
                            var planItems = dto.SelectedItemIds.Distinct().Select(itemId => new ProductionPlanItem
                            {
                                ProductionPlanId = productionPlan.Id,
                                ItemId = itemId,
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            }).ToList();

                            _context.ProductionPlanItems.AddRange(planItems);
                            await _context.SaveChangesAsync();

                            _context.ProductionPlanOperationLogs.Add(new ProductionPlanOperationLog
                            {
                                ProductionPlanId = productionPlan.Id,
                                Operator = operatorName,
                                OperationTime = DateTime.Now,
                                OperationContent = $"选择物品，共{planItems.Count}项",
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            });
                        }

                        // 5. 批量新增选择的销售订单 -> ProductionPlanSalesOrder（合并旧单个参数）
                        var salesOrderIds = new List<int>();
                        if (dto.SelectedSalesOrderIds?.Any() == true)
                            salesOrderIds.AddRange(dto.SelectedSalesOrderIds);
                        if (dto.SalesOrderId.HasValue)
                            salesOrderIds.Add(dto.SalesOrderId.Value);

                        if (salesOrderIds.Any())
                        {
                            salesOrderIds = salesOrderIds.Distinct().ToList();
                            var planSalesOrders = salesOrderIds.Select(soId => new ProductionPlanSalesOrder
                            {
                                ProductionPlanId = productionPlan.Id,
                                SalesOrderId = soId,
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            }).ToList();

                            _context.ProductionPlanSalesOrders.AddRange(planSalesOrders);
                            await _context.SaveChangesAsync();

                            _context.ProductionPlanOperationLogs.Add(new ProductionPlanOperationLog
                            {
                                ProductionPlanId = productionPlan.Id,
                                Operator = operatorName,
                                OperationTime = DateTime.Now,
                                OperationContent = $"关联销售订单，共{planSalesOrders.Count}个",
                                Creator = operatorName,
                                CreateTime = DateTime.Now
                            });
                        }

                        // 6. 记录新增生产计划操作日志
                        _context.ProductionPlanOperationLogs.Add(new ProductionPlanOperationLog
                        {
                            ProductionPlanId = productionPlan.Id,
                            Operator = operatorName,
                            OperationTime = DateTime.Now,
                            OperationContent = "新增生产计划",
                            Creator = operatorName,
                            CreateTime = DateTime.Now
                        });

                        await _context.SaveChangesAsync();
                        await transaction.CommitAsync();
                    }
                    catch
                    {
                        await transaction.RollbackAsync();
                        throw;
                    }
                });

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "生产计划新增成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = $"生产计划新增失败：{ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        public async Task<ApiResult<string>> UploadFileAsync(IFormFile file, int productionPlanId, string operatorName)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return new ApiResult<string>
                    {
                        Code = ApiEnum.Error,
                        Msg = "文件不能为空",
                        Data = null
                    };
                }

                // 检查生产计划是否存在
                var productionPlan = await _context.ProductionPlans
                    .FirstOrDefaultAsync(p => p.Id == productionPlanId && !p.IsDeleted);
                
                if (productionPlan == null)
                {
                    return new ApiResult<string>
                    {
                        Code = ApiEnum.Error,
                        Msg = "生产计划不存在",
                        Data = null
                    };
                }

                // 生成文件路径
                var uploadPath = Path.Combine("Uploads", "ProductionPlans", productionPlanId.ToString());
                var fullPath = Path.Combine(Directory.GetCurrentDirectory(), uploadPath);
                
                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }

                var fileName = $"{DateTime.Now:yyyyMMddHHmmss}_{file.FileName}";
                var filePath = Path.Combine(fullPath, fileName);
                var relativePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 保存附件记录
                var attachment = new ProductionPlanAttachment
                {
                    ProductionPlanId = productionPlanId,
                    FileName = file.FileName,
                    FilePath = relativePath,
                    Creator = operatorName,
                    CreateTime = DateTime.Now
                };

                _context.ProductionPlanAttachments.Add(attachment);

                // 记录操作日志
                var operationLog = new ProductionPlanOperationLog
                {
                    ProductionPlanId = productionPlanId,
                    Operator = operatorName,
                    OperationTime = DateTime.Now,
                    OperationContent = $"上传文件：{file.FileName}",
                    Creator = operatorName,
                    CreateTime = DateTime.Now
                };

                _context.ProductionPlanOperationLogs.Add(operationLog);
                await _context.SaveChangesAsync();

                return new ApiResult<string>
                {
                    Code = ApiEnum.Success,
                    Msg = "文件上传成功",
                    Data = relativePath
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<string>
                {
                    Code = ApiEnum.Error,
                    Msg = $"文件上传失败：{ex.Message}",
                    Data = null
                };
            }
        }

        public async Task<ApiResult<bool>> SoftDeleteAsync(int productionPlanId, string operatorName)
        {
            try
            {
                var plan = await _context.ProductionPlans.FirstOrDefaultAsync(x => x.Id == productionPlanId && !x.IsDeleted);
                if (plan == null)
                {
                    return new ApiResult<bool> { Code = ApiEnum.NotFound, Msg = "生产计划不存在", Data = false };
                }

                plan.IsDeleted = true;
                plan.Updator = operatorName;
                plan.UpdateTime = DateTime.Now;

                _context.ProductionPlanOperationLogs.Add(new ProductionPlanOperationLog
                {
                    ProductionPlanId = plan.Id,
                    Operator = operatorName,
                    OperationTime = DateTime.Now,
                    OperationContent = "逻辑删除生产计划",
                    Creator = operatorName,
                    CreateTime = DateTime.Now
                });

                await _context.SaveChangesAsync();
                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = ex.Message, Data = false };
            }
        }

        public async Task<ApiResult<ProductionPlanDetailDto>> GetDetailAsync(int productionPlanId)
        {
            try
            {
                var plan = await _context.ProductionPlans.FirstOrDefaultAsync(x => x.Id == productionPlanId && !x.IsDeleted);
                if (plan == null)
                    return new ApiResult<ProductionPlanDetailDto> { Code = ApiEnum.NotFound, Msg = "未找到" };

                var result = new ProductionPlanDetailDto
                {
                    Id = plan.Id,
                    PlanNumber = plan.PlanNumber,
                    PlanSubject = plan.PlanSubject,
                    DocumentDate = plan.DocumentDate,
                    SalesOrderId = plan.SalesOrderId,
                    ProjectId = plan.ProjectId,
                    Remarks = plan.Remarks,
                    Status = plan.Status,
                    IsBindSalesOrder = plan.IsBindSalesOrder,
                    Creator = plan.Creator,
                    CreateTime = plan.CreateTime,
                    Updator = plan.Updator,
                    UpdateTime = plan.UpdateTime
                };

                // 自由录入生产物品
                result.ProductedItems = await _context.ProductedItems
                    .Where(p => !p.IsDeleted && p.ProductionPlanId == plan.Id)
                    .Select(p => new ProductedItemDto
                    {
                        ItemNumber = p.ItemNumber,
                        ItemName = p.ItemName,
                        SpecificationModel = p.SpecificationModel,
                        Unit = p.Unit,
                        ItemCategory = p.ItemCategory,
                        ItemClassification = p.ItemClassification,
                        Brand = p.Brand,
                        Quantity = p.Quantity,
                        DetailDate = p.DetailDate,
                        MainUnitQuantity = p.MainUnitQuantity,
                        Remarks = p.Remarks
                    }).ToListAsync();

                // 附件
                result.Attachments = await _context.ProductionPlanAttachments
                    .Where(a => !a.IsDeleted && a.ProductionPlanId == plan.Id)
                    .Select(a => new ProductionPlanAttachmentDto
                    {
                        FileName = a.FileName,
                        FilePath = a.FilePath
                    }).ToListAsync();

                // 操作记录
                result.OperationLogs = await _context.ProductionPlanOperationLogs
                    .Where(l => !l.IsDeleted && l.ProductionPlanId == plan.Id)
                    .OrderByDescending(l => l.OperationTime)
                    .Select(l => new ProductionPlanOperationLogDto
                    {
                        Operator = l.Operator,
                        OperationTime = l.OperationTime,
                        OperationContent = l.OperationContent
                    }).ToListAsync();

                return new ApiResult<ProductionPlanDetailDto> { Code = ApiEnum.Success, Msg = "查询成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionPlanDetailDto> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        public async Task<ApiResult<byte[]>> ExportPlanAsync(int productionPlanId)
        {
            try
            {
                // 忽略传入的单个ID，导出全部生产计划
                var plans = await _context.ProductionPlans
                    .Where(p => !p.IsDeleted)
                    .Include(p => p.SalesOrder)
                    .Include(p => p.Project)
                    .OrderByDescending(p => p.CreateTime)
                    .ToListAsync();

                var planIds = plans.Select(p => p.Id).ToList();
                var productedItems = await _context.ProductedItems
                    .Where(i => !i.IsDeleted && planIds.Contains(i.ProductionPlanId))
                    .ToListAsync();

                Directory.CreateDirectory(ExportRoot);
                var file = Path.Combine(ExportRoot, $"plans_all_{DateTime.Now:yyyyMMddHHmmss}.xlsx");

                using (XSSFWorkbook wb = new XSSFWorkbook())
                {
                    // Sheet1: Plans 基本信息
                    var wsPlans = wb.CreateSheet("Plans");
                    int r = 0;
                    var planHeaders = new[] { "ID","计划单号","计划主题","单据日期","关联销售订单","关联项目","备注","状态","是否绑定销售单","创建人","创建时间","最后修改人","最后修改时间" };
                    var hr = wsPlans.CreateRow(r++);
                    for (int i = 0; i < planHeaders.Length; i++) hr.CreateCell(i).SetCellValue(planHeaders[i]);
                    foreach (var p in plans)
                    {
                        var row = wsPlans.CreateRow(r++);
                        int c = 0;
                        row.CreateCell(c++).SetCellValue(p.Id);
                        row.CreateCell(c++).SetCellValue(p.PlanNumber);
                        row.CreateCell(c++).SetCellValue(p.PlanSubject);
                        row.CreateCell(c++).SetCellValue(p.DocumentDate.ToString("yyyy-MM-dd"));
                        row.CreateCell(c++).SetCellValue(p.SalesOrder?.SalesOrderSubject ?? "");
                        row.CreateCell(c++).SetCellValue(p.Project?.ProjectName ?? "");
                        row.CreateCell(c++).SetCellValue(p.Remarks ?? "");
                        row.CreateCell(c++).SetCellValue(p.Status);
                        row.CreateCell(c++).SetCellValue(p.IsBindSalesOrder ? "是" : "否");
                        row.CreateCell(c++).SetCellValue(p.Creator ?? "");
                        row.CreateCell(c++).SetCellValue(p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        row.CreateCell(c++).SetCellValue(p.Updator ?? "");
                        row.CreateCell(c++).SetCellValue(p.UpdateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "");
                    }
                    for (int i = 0; i < planHeaders.Length; i++) wsPlans.AutoSizeColumn(i);

                    // Sheet2: ProductedItems 汇总
                    var wsItems = wb.CreateSheet("ProductedItems");
                    var itemHeaders = new[] { "计划ID","计划单号","物品编号","物品名称","规格型号","单位","物品类别","物品分类","品牌","数量","详情日期","主单位数量","备注" };
                    var h2 = wsItems.CreateRow(0);
                    for (int i = 0; i < itemHeaders.Length; i++) h2.CreateCell(i).SetCellValue(itemHeaders[i]);
                    int r2 = 1;
                    var planNoMap = plans.ToDictionary(p => p.Id, p => p.PlanNumber);
                    foreach (var it in productedItems)
                    {
                        var row = wsItems.CreateRow(r2++);
                        int c = 0;
                        row.CreateCell(c++).SetCellValue(it.ProductionPlanId);
                        row.CreateCell(c++).SetCellValue(planNoMap.TryGetValue(it.ProductionPlanId, out var no) ? no : "");
                        row.CreateCell(c++).SetCellValue(it.ItemNumber);
                        row.CreateCell(c++).SetCellValue(it.ItemName);
                        row.CreateCell(c++).SetCellValue(it.SpecificationModel);
                        row.CreateCell(c++).SetCellValue(it.Unit);
                        row.CreateCell(c++).SetCellValue(it.ItemCategory);
                        row.CreateCell(c++).SetCellValue(it.ItemClassification);
                        row.CreateCell(c++).SetCellValue(it.Brand ?? "");
                        row.CreateCell(c++).SetCellValue(it.Quantity);
                        row.CreateCell(c++).SetCellValue(it.DetailDate?.ToString("yyyy-MM-dd") ?? "");
                        row.CreateCell(c++).SetCellValue(it.MainUnitQuantity?.ToString() ?? "");
                        row.CreateCell(c++).SetCellValue(it.Remarks ?? "");
                    }
                    for (int i = 0; i < itemHeaders.Length; i++) wsItems.AutoSizeColumn(i);

                    // 转换为字节数组
                    using var ms = new MemoryStream();
                    wb.Write(ms);
                    return new ApiResult<byte[]> { Code = ApiEnum.Success, Msg = "导出成功", Data = ms.ToArray() };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<byte[]> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        public async Task<ApiResult<byte[]>> ExportProductedItemsAsync(int productionPlanId)
        {
            try
            {
                var items = await _context.ProductedItems
                    .Where(p => !p.IsDeleted && p.ProductionPlanId == productionPlanId)
                    .ToListAsync();

                using var wb = new XSSFWorkbook();
                var ws = wb.CreateSheet("生产物品");
                var headers = new[] { "物品编号","物品名称","规格型号","单位","物品类别","物品分类","品牌","数量","详情日期","主单位数量","备注" };
                var hr = ws.CreateRow(0);
                for (int i = 0; i < headers.Length; i++) hr.CreateCell(i).SetCellValue(headers[i]);
                int r = 1;
                foreach (var p in items)
                {
                    var row = ws.CreateRow(r++);
                    int c = 0;
                    row.CreateCell(c++).SetCellValue(p.ItemNumber);
                    row.CreateCell(c++).SetCellValue(p.ItemName);
                    row.CreateCell(c++).SetCellValue(p.SpecificationModel);
                    row.CreateCell(c++).SetCellValue(p.Unit);
                    row.CreateCell(c++).SetCellValue(p.ItemCategory);
                    row.CreateCell(c++).SetCellValue(p.ItemClassification);
                    row.CreateCell(c++).SetCellValue(p.Brand ?? "");
                    row.CreateCell(c++).SetCellValue(p.Quantity);
                    row.CreateCell(c++).SetCellValue(p.DetailDate?.ToString("yyyy-MM-dd") ?? "");
                    row.CreateCell(c++).SetCellValue(p.MainUnitQuantity?.ToString() ?? "");
                    row.CreateCell(c++).SetCellValue(p.Remarks ?? "");
                }
                for (int i = 0; i < headers.Length; i++) ws.AutoSizeColumn(i);

                // 转换为字节数组
                using var ms = new MemoryStream();
                wb.Write(ms);
                return new ApiResult<byte[]> { Code = ApiEnum.Success, Msg = "导出成功", Data = ms.ToArray() };
            }
            catch (Exception ex)
            {
                return new ApiResult<byte[]> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        public async Task<ApiResult<byte[]>> ExportOperationLogsAsync(int productionPlanId)
        {
            try
            {
                var logs = await _context.ProductionPlanOperationLogs
                    .Where(l => !l.IsDeleted && l.ProductionPlanId == productionPlanId)
                    .OrderByDescending(l => l.OperationTime)
                    .ToListAsync();

                using var wb = new XSSFWorkbook();
                var ws = wb.CreateSheet("操作记录");
                var hr = ws.CreateRow(0);
                hr.CreateCell(0).SetCellValue("操作时间");
                hr.CreateCell(1).SetCellValue("操作人");
                hr.CreateCell(2).SetCellValue("操作内容");
                int r = 1;
                foreach (var l in logs)
                {
                    var row = ws.CreateRow(r++);
                    row.CreateCell(0).SetCellValue(l.OperationTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    row.CreateCell(1).SetCellValue(l.Operator);
                    row.CreateCell(2).SetCellValue(l.OperationContent);
                }
                ws.AutoSizeColumn(0); ws.AutoSizeColumn(1); ws.AutoSizeColumn(2);

                // 转换为字节数组
                using var ms = new MemoryStream();
                wb.Write(ms);
                return new ApiResult<byte[]> { Code = ApiEnum.Success, Msg = "导出成功", Data = ms.ToArray() };
            }
            catch (Exception ex)
            {
                return new ApiResult<byte[]> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 分页查询生产计划
        /// </summary>
        public async Task<ApiResult<ProductionPlanPageResultDto>> GetProductionPlansPageAsync(ProductionPlanQueryDto queryDto)
        {
            try
            {
                var query = _context.ProductionPlans
                    .Where(p => !p.IsDeleted)
                    .Include(p => p.SalesOrder)
                    .Include(p => p.Project)
                    .AsQueryable();

                // 应用查询条件
                if (!string.IsNullOrWhiteSpace(queryDto.PlanNumber))
                {
                    query = query.Where(p => p.PlanNumber.Contains(queryDto.PlanNumber));
                }

                if (!string.IsNullOrWhiteSpace(queryDto.PlanSubject))
                {
                    query = query.Where(p => p.PlanSubject.Contains(queryDto.PlanSubject));
                }

                if (queryDto.DocumentDateStart.HasValue)
                {
                    query = query.Where(p => p.DocumentDate >= queryDto.DocumentDateStart.Value);
                }

                if (queryDto.DocumentDateEnd.HasValue)
                {
                    query = query.Where(p => p.DocumentDate <= queryDto.DocumentDateEnd.Value);
                }

                if (!string.IsNullOrWhiteSpace(queryDto.Status))
                {
                    query = query.Where(p => p.Status == queryDto.Status);
                }

                // 获取总记录数
                var totalCount = await query.CountAsync();

                // 计算总页数
                var totalPages = (int)Math.Ceiling((double)totalCount / queryDto.PageSize);

                // 分页查询
                var items = await query
                    .OrderByDescending(p => p.CreateTime)
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select(p => new ProductionPlanListItemDto
                    {
                        Id = p.Id,
                        PlanNumber = p.PlanNumber,
                        PlanSubject = p.PlanSubject,
                        DocumentDate = p.DocumentDate,
                        SalesOrderSubject = p.SalesOrder != null ? p.SalesOrder.SalesOrderSubject : null,
                        ProjectName = p.Project != null ? p.Project.ProjectName : null,
                        Remarks = p.Remarks,
                        Status = p.Status,
                        IsBindSalesOrder = p.IsBindSalesOrder,
                        Creator = p.Creator,
                        CreateTime = p.CreateTime,
                        Updator = p.Updator,
                        UpdateTime = p.UpdateTime
                    })
                    .ToListAsync();

                var result = new ProductionPlanPageResultDto
                {
                    TotalCount = totalCount,
                    TotalPages = totalPages,
                    PageIndex = queryDto.PageIndex,
                    PageSize = queryDto.PageSize,
                    Items = items
                };

                return new ApiResult<ProductionPlanPageResultDto> { Code = ApiEnum.Success, Msg = "查询成功", Data = result };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProductionPlanPageResultDto> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 导出生产计划列表（支持查询条件）
        /// </summary>
        public async Task<ApiResult<byte[]>> ExportProductionPlansAsync(ProductionPlanQueryDto queryDto)
        {
            try
            {
                var query = _context.ProductionPlans
                    .Where(p => !p.IsDeleted)
                    .Include(p => p.SalesOrder)
                    .Include(p => p.Project)
                    .AsQueryable();

                // 应用查询条件
                if (!string.IsNullOrWhiteSpace(queryDto.PlanNumber))
                {
                    query = query.Where(p => p.PlanNumber.Contains(queryDto.PlanNumber));
                }

                if (!string.IsNullOrWhiteSpace(queryDto.PlanSubject))
                {
                    query = query.Where(p => p.PlanSubject.Contains(queryDto.PlanSubject));
                }

                if (queryDto.DocumentDateStart.HasValue)
                {
                    query = query.Where(p => p.DocumentDate >= queryDto.DocumentDateStart.Value);
                }

                if (queryDto.DocumentDateEnd.HasValue)
                {
                    query = query.Where(p => p.DocumentDate <= queryDto.DocumentDateEnd.Value);
                }

                if (!string.IsNullOrWhiteSpace(queryDto.Status))
                {
                    query = query.Where(p => p.Status == queryDto.Status);
                }

                var plans = await query
                    .OrderByDescending(p => p.CreateTime)
                    .ToListAsync();

                using var wb = new XSSFWorkbook();
                
                // Sheet1: 生产计划基本信息
                var wsPlans = wb.CreateSheet("生产计划");
                int r = 0;
                var planHeaders = new[] { "ID", "计划单号", "计划主题", "单据日期", "关联销售订单", "关联项目", "备注", "状态", "是否绑定销售单", "创建人", "创建时间", "最后修改人", "最后修改时间" };
                var hr = wsPlans.CreateRow(r++);
                for (int i = 0; i < planHeaders.Length; i++) hr.CreateCell(i).SetCellValue(planHeaders[i]);
                
                foreach (var p in plans)
                {
                    var row = wsPlans.CreateRow(r++);
                    int c = 0;
                    row.CreateCell(c++).SetCellValue(p.Id);
                    row.CreateCell(c++).SetCellValue(p.PlanNumber);
                    row.CreateCell(c++).SetCellValue(p.PlanSubject);
                    row.CreateCell(c++).SetCellValue(p.DocumentDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(c++).SetCellValue(p.SalesOrder?.SalesOrderSubject ?? "");
                    row.CreateCell(c++).SetCellValue(p.Project?.ProjectName ?? "");
                    row.CreateCell(c++).SetCellValue(p.Remarks ?? "");
                    row.CreateCell(c++).SetCellValue(p.Status);
                    row.CreateCell(c++).SetCellValue(p.IsBindSalesOrder ? "是" : "否");
                    row.CreateCell(c++).SetCellValue(p.Creator ?? "");
                    row.CreateCell(c++).SetCellValue(p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    row.CreateCell(c++).SetCellValue(p.Updator ?? "");
                    row.CreateCell(c++).SetCellValue(p.UpdateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "");
                }
                
                for (int i = 0; i < planHeaders.Length; i++) wsPlans.AutoSizeColumn(i);

                // 转换为字节数组
                using var ms = new MemoryStream();
                wb.Write(ms);
                return new ApiResult<byte[]> { Code = ApiEnum.Success, Msg = "导出成功", Data = ms.ToArray() };
            }
            catch (Exception ex)
            {
                return new ApiResult<byte[]> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }
    }
} 